package co.yixiang.modules.websocket;


import co.yixiang.modules.system.service.UserService;
import co.yixiang.modules.system.service.dto.UserDto;
import co.yixiang.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@ServerEndpoint("/webSocket")
@Component
public class WebSocketEndpoint {

    //与某个客户端的连接绘画，需要通过他来个客户端发送数据
    private Session session;

    @Autowired
    private UserService userService;

    /**
     * 连接成功调用的方法
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId){
        //把会话存入到连接池中
//        UserDto user = userService.findByName(SecurityUtils.getUsername());
        SessionPool.sessions.put("username",session);
        Timer timer = new Timer();
        timer.schedule(new Mytask(),1000,1000);//1s执行一次
    }

    class Mytask extends TimerTask {
        @Override
        public void run() {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            SessionPool.sendMessage(sdf.format(new Date()));
        }
    }

    /**
     * 关闭连接
     * @param session
     */
    @OnClose
    public void onClose(Session session) throws IOException {
        SessionPool.close(session.getId());
        session.close();
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        SessionPool.sendMessage(message);
    }
}
